<?php

namespace App\Http\Controllers;

use App\Model\Info;
use App\Model\Record;
use App\Model\Send;
use App\Model\Province;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use SoapBox\Formatter\Formatter;
use Excel;

class TestController extends Controller
{

    const modles = array(
        '004020' => '全新致炫',
        '004021' => '致享',
        '004001' => '凯美瑞',
        '004002' => '汉兰达',
        '004013' => '致炫',
        '004014' => '雷凌',
        '004019' => '雷凌双擎',
        '004015' => '凯美瑞双擎',
    );

    public function check($data){
        $infos=array();
        if(!empty($data["city"])) {
            if (preg_match("/[\x7f-\xff]/", $data["province"]) && !empty($data["province"])) {
                $data["province"] = $data["province"];
            } else {
                $data["province"] = Province::pro_name($data["province"]);
            }
        }
        if(!empty($data["city"])){


        if (preg_match("/[\x7f-\xff]/", $data["city"])) {
            $data["city"]=$data["city"];
        }else{
            $data["city"] = Province::city_name($data["city"]);
        }

        }
        if(!empty($data["shop"])){
        if (preg_match("/[\x7f-\xff]/", $data["shop"]) && !empty($data["shop"])) {
            $data["shop"] = $data["shop"];
        }else{
            $data["shop"]=Province::shop_name($data["shop"]);
        }
        }
        if(!empty($data["type"])){
        if (preg_match("/[\x7f-\xff]/", $data["type"]) && !empty($data["type"])) {
            $data["type"] =$data["type"];
        }else{
            $data["type"] = self::modles[$data["type"]];
        }
        }
        return $data;
    }

    public  function  shai(){


        include public_path("/sms/TopSdk.php");
        date_default_timezone_set('Asia/Shanghai');

        $code = '{"code":"123456789"}';

        $c = new \TopClient();
        $c ->appkey = '23757410' ;
        $c ->secretKey = "4dd822f6ae64faa9359495e8ba266b2f" ;
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req ->setExtend( "" );
        $req ->setSmsType( "normal" );
        $req ->setSmsFreeSignName( "广丰商城丰云惠" );
        $req->setSmsParam($code);
        $req ->setRecNum( "15801053634" );
        $req ->setSmsTemplateCode( "SMS_62430279" );
        $resp = $c ->execute( $req );

        $rest = $resp->result;

        if($rest->success == true){
            echo 1;
        }





//
//        $list = DB::table("c")->get();
//        foreach ($list as $val){
//            Redis::sadd('code_you',$val->code);
//        }

    }

    public function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        } if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }

    public function export(){


//        $list = DB::table("sendinfo")->rightjoin("sendinfo5","sendinfo5.phone","=","sendinfo.phone")->whereNull("sendinfo.phone")->get(["sendinfo5.code","sendinfo5.name","sendinfo5.phone","sendinfo5.shop"]);
//        $list= $this->object_array($list);
//
//
//        DB::table("sendinfo")->insert($list["\x00*\x00items"]);
//        dd($list);
//
//        die;
//        DB::listen(function ($sql){
////dump($sql);
////            where(DB::raw("length(infos.province)"),DB::raw("char_length(infos.province)"))->take(10)
//        });
        $data='';
        $list = Info::get(["infos.*"]);
        $list = $list->toarray();
        foreach($list as $key => $val){
            $list[$key] = $this->check($val);
        }
//        $l = Redis::smembers("code_e");
//        $list=array();
//        foreach ($l as $value){
//        $list[]=array($value);
//        }

//        dd($list);
        Excel::create('Filename', function($excel) use($list) {
            $excel->sheet('Sheetname', function($sheet) use ($list) {
                $sheet->fromArray($list);
            });

        })->export('xls');
    }

    public  function  import(){
//        Excel::load(storage_path("1.xlsx"), function($reader) {
////echo 1;
//            // Getting all results
//            $results = $reader->get();
////            dd($results);
//
//        });

        Excel::load(storage_path("card512.xlsx"), function($reader) {

            $data = $reader->toArray();
//            dd($data);
//            $data=$data[0];
//            $d=array();
//            foreach ($data as $key =>$val){
////                dump($val);
////                unset($data[$key][""]);
//                array_pop($data[$key]);
//
////                $d[$key]["code"]=$val["code"];
//            }
//            dd($data);
//            dd($d);
//            DB::table("card")->insert($data);


        })->get();
    }
    public function  sendcard(){
//        $infos = DB::table("sendinfo")->skip(800)->take(400)->get();
//        $infos = DB::table("sendinfo")->rightjoin("sendinfo5","sendinfo5.phone","=","sendinfo.phone")->whereNull("sendinfo.phone")->get(["sendinfo5.phone"])->toarray();
//
//        $cards = DB::table("card")->skip(0)->take(400)->get();
        echo "<pre>";
//        dd($infos,$cards);

        foreach ($infos as $key =>$val){
//            dd($val);
//            $val->card=$cards[$key];

//            echo json_encode($val);
//            echo json_encode($cards[$key]);
//
//            echo "<br />";

            $content ='【广丰商城丰云惠】恭喜您在“福利大轮盘”活动中，获得价值50元京东e卡一张。卡券：'.$val->card.'，密码：'.$val->pass.'，有效期为即日起一年,感谢您的参与！';

//            $content='【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值50元京东e卡一张。卡券：'.$cards[$key]->card.'，密码：'.$cards[$key]->pass.'，有效期为即日起一年。使用京东App，点击“我的钱包”-“京东卡/E卡”-“绑定新卡”即可使用，感谢您的参与！丰云惠海量福利持续放送，敬请持续关注，销售信息详询客服电话：400-830-8888转1';


            echo $url='http://sdk4rptws.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=6SDK-EMY-6688-KIZNL&password=020521&phone='.$val->phone.'&message='.$content;
            Log::info($url);
            echo "<br />";
//            $rets='0';
//            $rets=0;
            $rets= $this->curlget($url);

            if(intval($rets)=='0'){
//                $infos = DB::table("sendinfo")->where("id",$val->id)->update(array("card"=>$val->card,'pass'=>$val->pass));
//                $infos = DB::table("sendinfo")->where("id",$val->id)->update(array("card"=>$cards[$key]->card,'pass'=>$cards[$key]->pass));
//                DB::table("card")->where("card",$cards[$key]->card)->update(["act"=>'1']);
                Log::info($val->phone.'发送成功');
            }
//            die;

        }


}

    public function test()
    {

//        echo "<img src='".asset('/storage/turn.png')."'>";die;

//        Redis::set("testnum",'0');
//        echo  Redis::get("testnum");
//        Redis::incr("testnum");
//        echo  Redis::get("testnum");
//        Redis::incr("testnum",'2');
//       echo  Redis::get("testnum");die;

//        $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
//        echo array_search("Dog",$a);
//        die;
////        $arr = array("name"=>'1');
////        echo json_encode($arr);die;
////        echo date("yyyy-MM-dd HH:mm:ss");die;
//         $time=date("YmdHis").rand(1000,9999);
//
//       echo  $info = '[
//    {
//        "media_code": "f01ca4ea-858c-4241-8414-5066ac20caad",
//        "clue_code": "'.$time.'",
//        "dealer_code": "42A22",
//        "is_publicorder": 1,
//        "clue_type": 1,
//        "modle_code": "004014",
//        "modle_name": "",
//        "series_code": "",
//        "series_name": "",
//        "province_code": "062003",
//        "province_name": "湖北省",
//        "city_code": "062003006",
//        "city_name": "武汉市",
//        "district_code": "",
//        "district_name": "",
//        "content": "",
//        "create_time": "'.date("Y-m-d H:i:s").'",
//        "status": 0,
//        "customer_name": "测试tt",
//        "gender": "",
//        "phone": "15810982548",
//        "business_phone": "",
//        "mobile": "",
//        "email": "",
//        "address": "",
//        "contact_method": "",
//        "fax": "",
//        "buy_date": "",
//        "communication_time": "",
//        "pre_fetch_time": "",
//        "pre_payment_method": "",
//        "arrangement": "",
//        "pre_time": "",
//        "promotion_price": "",
//        "remark": "",
//        "add": ""
//    }
//]';
//        $url="http://gcloudtest.gac-toyota.com.cn:8005/GCloudWebService.asmx/SetSalesLeads";
//
//        $arr="media_code=f01ca4ea-858c-4241-8414-5066ac20caad&Interface_name=Interface_salesleads&jsonstring=".$info;
//
//        $pro = $this->get_url_contents($url,$arr);
//////        $pdata = json_decode($pro);
////        dd($pro);
////        $data=array();
//        $p =  DB::table("modles")->pluck("dealer_name","dealer_code");
//        print_R(json_encode($p));
//        die;
//        echo json_encode($p);
//        die;
////
////        foreach ($p as $val){
////            $list = DB::table("city")->where("city_code", 'like', $val->province_code . "%")->where("status", "True")->get(["city_name", "city_code"]);
////            $data[$val->province_code]=$list;
////        }
//
//        $list = DB::table("city")->where("status", "True")->get(["city_name", "city_code"]);
//        foreach ($list as $v){
//            $s = DB::table("shop")->where("dealer_city_code", $v->city_code)->get(["dealer_name"]);
//            $data[$v->city_code]=$s;
//            }
//
//        dd(json_encode($data));

        $id = $_SESSION["id"];
        Info::where("user_id", $id)->delete();
        Record::where("user_id", $id)->delete();
        User::where("id", $id)->update(['nums' => '1', 'win_num' => '0']);

        echo "<script>var storage = window.localStorage;storage.a=0;</script>";

        echo '成功';
//        return view("test");
    }

    public function sendsms(Request $request){

        $phone = '18613519599';
        $hxcode = '170184276';
        $prize ='1';

//        $list = DB::table("barrage")->where("time",">",'2017-3-20 18:00:00')->get();

//        foreach ($list as $val){
//            $prize = substr( $val->code, 0, 1 )=='1'?'1':"3";
//            $hxcode=$val->code;
//            $phone=$val->phone;

        //发送核销码
        if($prize=='0'){
            $content ='【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值1000元油卡一张。核销码为：';
//            $content = '尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值50元京东e卡一张。卡券：JDV14979145001438，密码：DE5E-BC67-ADE1-A0E2，有效期为即日起一年。使用京东App，点击“我的钱包”-“京东卡/E卡”-“绑定新卡”即可使用，感谢您的参与！';
//            $hxcode = Redis::spop("code_you");
//            $content = '尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值1000元油卡一张。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店，购买雷凌Turbo并在店内购买交强险，且购车发票日期需为3月15日至5月10日，方能成功兑换油卡，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='1'){

//            $content = '1';
//            $hxcode = Redis::spop("code_you");
            $content = '【广丰商城丰云惠】尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值1000元油卡一张。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店，购买雷凌Turbo并在店内购买交强险，且购车发票日期需为3月15日至5月10日，方能成功兑换油卡，感谢您的参与。';
        }
        if($prize=='2'){
//            $hxcode = Redis::spop("code_xiaomi");
            $content = '尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值149元小米手环一支。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，我方将于您到店核销后15个工作日内将奖品寄出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='3'){
//            $hxcode = Redis::spop("code_e");
            $content = '尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值50元京东e卡一张。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，京东e卡的卡券和密码将会在到店核销后15个工作日内以短信形式发出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='4'){
//            $hxcode = Redis::spop("code_ipad");
            $content = '尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值2888元iPad mini 4一台。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，我方将于您到店核销后15个工作日内将奖品寄出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }
        if($prize=='5'){
//            $hxcode = Redis::spop("code_tent");
            $content = '尊敬的用户，恭喜您在“福利大轮盘”活动中，获得价值599元户外帐篷一个。核销码为：'.$hxcode.'，凭此码在即日起14日内到广汽丰田销售店进行核销，我方将于您到店核销后15个工作日内将奖品寄出，感谢您的参与。销售信息详询客服电话：400-830-8888转1';
        }


       echo  $url='http://sdk4rptws.eucp.b2m.cn:8080/sdkproxy/sendsms.action?cdkey=6SDK-EMY-6688-KIZNL&password=020521&phone='.$phone.'&message='.$content;

//echo "<br />";
        echo   $rets= $this->curlget($url);

        dd($rets);

//        }
//        dd($list);





    }

    public function get_real_ip()
    {

        $ip = false;

        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {

            $ip = $_SERVER['HTTP_CLIENT_IP'];

        }

        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

            $ips = explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR']);

            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }

            for ($i = 0; $i < count($ips); $i++) {

                if (!eregi('^(10│172.16│192.168).', $ips[$i])) {

                    $ip = $ips[$i];

                    break;

                }

            }

        }

        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);

    }

    public function getip()
    {
        echo $this->get_real_ip() . '  /  ';

        echo $_SERVER["REMOTE_ADDR"];
    }

    public function send()
    {


        $pro = $this->curlget("http://gcloudintf.gac-toyota.com.cn:8002/GCloudWebService.asmx/GetINFOBYMEDIA?media_code=91de4f09-9a2d-4b4e-9ed9-0a0318633859&Interface_name=Interface_province&Conduct_type=1");
        $pdata = json_decode($pro);

        foreach ($pdata as $value){
            DB::table("province")->insert(array('province_name'=>$value->province_name,'province_code'=>$value->province_code,'status'=>$value->status));
        }
        $pro = $this->curlget("http://gcloudintf.gac-toyota.com.cn:8002/GCloudWebService.asmx/GetINFOBYMEDIA?media_code=91de4f09-9a2d-4b4e-9ed9-0a0318633859&Interface_name=Interface_city&Conduct_type=1");
        $cdata = json_decode($pro);

        foreach ($cdata as $value){
            DB::table("city")->insert(array('city_name'=>$value->city_name,'city_code'=>$value->city_code,'status'=>$value->status));
        }
        $pro = $this->curlget("http://gcloudintf.gac-toyota.com.cn:8002/GCloudWebService.asmx/GetINFOBYMEDIA?media_code=91de4f09-9a2d-4b4e-9ed9-0a0318633859&Interface_name=Interface_dealers&Conduct_type=1");
        $ddata = json_decode($pro);

        foreach ($ddata as $value){
            DB::table("shop")->insert(array('dealer_name'=>$value->dealer_name,'dealer_code'=>$value->dealer_code,'status'=>$value->status,'dealer_province_code'=>$value->dealer_province_code,'dealer_city_code'=>$value->dealer_city_code));
        }

        $pro = $this->curlget("http://gcloudintf.gac-toyota.com.cn:8002/GCloudWebService.asmx/GetINFOBYMEDIA?media_code=91de4f09-9a2d-4b4e-9ed9-0a0318633859&Interface_name=Interface_modle&Conduct_type=1");
        $ddata = json_decode($pro);
//        dd($ddata);

        foreach ($ddata as $value) {
            DB::table("modles")->insert(array('modle_name' => $value->modle_name, 'modle_code' => $value->modle_code, 'status' => $value->status, 'modle_name_en' => $value->modle_name_en, 'brand_code' => $value->brand_code));
        }
        dd($ddata);

        //http://gcloudtest.gac-toyota.com.cn:8005/GCloudWebService.asmx?GetINFOBYMEDIA
//       $send = new Send();
//        $send->login();
//        $send->sendSMS("15810882540",'123456');

//        $emay = new Emay();
//        $emay -> sendSMS("15810882540",'123456');
    }

    /**
     * curl post
     * @param type $url
     * @return json
     * @author wx
     */
    public function get_url_contents($url,$post_data=''){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, POST);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);// 设为TRUE把curl_exec()结果转化为字符串，而不是直接输出
        $tmpInfo = curl_exec($ch);
        dd($tmpInfo);
        curl_close($ch);
        return json_decode($tmpInfo,true);
    }

    //curl请求
    public function curlget($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_USERAGENT, "");
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
//        dd($res);
        curl_close($curl);
        return $res;
    }

    public function get_random($len = 3)
    {
        //range 是将10到99列成一个数组
        $numbers = range(10, 99);
        //shuffle 将数组顺序随即打乱
        shuffle($numbers);
        //取值起始位置随机
        $start = mt_rand(1, 10);
        //取从指定定位置开始的若干数
        $result = array_slice($numbers, $start, $len);
        $random = "";
        for ($i = 0; $i < $len; $i++) {
            $random = $random . $result[$i];
        }
        return $random;
    }

//随机数
    public function get_random2($length = 4)
    {
        $min = pow(10, ($length - 1));
        $max = pow(10, $length) - 1;
        return mt_rand($min, $max);
    }


    public function tocode()
    {
        for ($i = 0 ; $i < 5000; $i++) {
            $this->code();
        }
    }

    public function code()
    {
        $code = '8' . $this->get_random2(8);
        $count = DB::table("code")->where("code", $code)->count();
        if ($count) {
            $this->code();
        } else {
            DB::table("code2")->insert(array("code" => $code,'pid'=>'3'));
        }
    }

    public  function  savecode(){
//        $list = DB::table("code")->where("pid",'3')->get();
//        foreach ($list as $val){
//            Redis::sadd('code_e',$val->code);
//        }
//
//        $list = DB::table("codes")->get();
//        foreach ($list as $val){
//            Redis::sadd('code_you',$val->code);
//        }
//
        $list = DB::table("code")->where("pid",'2')->get();
        foreach ($list as $val){
            Redis::sadd('code_xiaomi',$val->code);
        }
//
        $list = DB::table("code")->where("pid",'4')->get();
        foreach ($list as $val){
            Redis::sadd('code_ipad',$val->code);
        }

        $list = DB::table("code")->where("pid",'5')->get();
        foreach ($list as $val){
            Redis::sadd('code_tent',$val->code);
        }



    }
}
